package main

import (
	"bytes"
	"flag"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync"
)

// 图片文件下载器
func main() {
	var url, newName, savePath string
	flag.StringVar(&url, "url", "", "图片url")
	flag.StringVar(&newName, "newName", "", "图片新名称")
	flag.StringVar(&savePath, "path", "./images", "图片存储路径")
	flag.Parse()
	savePath, _ = filepath.Abs(savePath)
	if err := PathExists(savePath); err != nil {
		panic(err)
	}

	if !strings.Contains(url, "http") {
		panic("url 格式错误,Example: http://www.xxx.com/images/a.jpg")
	}
	var images = strings.Split(url, ",")

	if len(images) > 1 {
		newName = ""
	}

	wg := &sync.WaitGroup{}
	for _, image := range images {
		wg.Add(1)
		go download(wg, image, newName, savePath)
	}
	wg.Wait()
}

func download(wg *sync.WaitGroup, url, newName, savePath string) {
	defer wg.Done()
	var fullPath = ""
	if newName != "" {
		fullPath = path.Join(savePath, newName)
	} else {
		fullPath = path.Join(savePath, path.Base(url))
	}
	//图片正则
	//println(path.Ext(imagPath))
	//通过http请求获取图片的流文件
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	out, err := os.Create(fullPath)
	if err != nil {
		panic(err)
	}
	if _, err := io.Copy(out, bytes.NewReader(body)); err != nil {
		panic(err)
	}

}

//PathExists 判断目录是否存在,没有则创建
func PathExists(path string) (err error) {
	_, err = os.Stat(path)
	if err == nil {
		return
	}
	if os.IsNotExist(err) {
		if err = os.Mkdir(path, os.ModePerm); err != nil {
			return
		}
		return nil
	}
	return err
}
